# coding=utf-8

from pymongo import MongoClient
from bs4 import BeautifulSoup
import requests
import datetime
import pprint
import json
import time
import re

server_client = MongoClient('127.0.0.1', 27017)

server_db = server_client['knx_posts_db']
offical_posts_coll = server_db['offical_posts_coll']


class POST():
    def __init__(self):
        self.company = '美团-大众点评'
        self.url = "https://campus.meituan.com/api/job/list/get"
        self.params = {

        }
        self.payload = {
            "jobType": "1",
            "workCity": [],
            "interviewCity": [],
            "jobFamily": None,
            "page": {
                "pageNo": 1,
                "pageSize": 8
            }
        }
        self.headers = {
            'Accept': 'application/json',
            'Accept-Encoding': 'gzip, deflate, br',
            'Accept-Language': 'zh-CN, zh;q=0.9',
            'Connection': 'keep-alive',
            'Content-Length': '98',
            'Content-Type': 'application/json',
            'Host': 'campus.meituan.com',
            'Origin': 'https://campus.meituan.com',
            'Referer': 'https://campus.meituan.com/jobs',
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.186 Safari/537.36',
            'X-Requested-With': 'XMLHttpRequest'
        }
        self.scrapy()

    def scrapy(self):
        r = requests.post(self.url, data = json.dumps(self.payload), headers = self.headers)
        j = r.json()
        for i in range(1, j['data']['page']['totalPageCount']):
            self.payload['page']['pageNo'] = i
            r = requests.post(self.url, data = json.dumps(self.payload), headers = self.headers)
            j = r.json()
            for job in j['data']['dataList']:
                url = 'https://campus.meituan.com/jobs?jobId=' + str(job['jobId']) + '&jobType=1&pageNo=' + str(i)
                name = job['jobName'].strip()
                location = job['workCity'].strip()
                count = ''
                edu = ''
                date = ''
                r = requests.post('https://campus.meituan.com/api/job/detail/get', data = json.dumps({'id': str(job['jobId'])}), headers = self.headers)
                detail = r.json()
                description = '岗位职责\n' + detail['data']['jobDuty'] + '\n任职要求\n' + detail['data']['requirement']
                item = {
                    "url": url,  # jd详情页的地址
                    'edu': edu,  # 最低学历
                    'exp': [],  # 所需工作经验，比如[3, 5]表示3到5年, [3]表示3年，[]表示无经验要求
                    'name': name,  # 职位名称 *
                    'date': date,  # 职位发布日期，字符串形式即可，后期统一转换
                    'lang': '',  # 对语言的要求
                    'place': '',  # 办公具体地址
                    'major': '',  # 专业要求
                    'count': count,  # 招聘数量
                    'salary': [],  # 薪资待遇，[5000, 8000]表示月薪5到8千，[4000]表示4千，[]表示没有写明
                    'toSchool': True,  # 是否是面向校园招聘，本次官网抓取一律都是校园招聘，所以此处都是True
                    'welfare': [],  # 福利待遇，比如五险一金、十三薪之类的，保存成数组
                    'funType': '',  # 职能类型，比如证券经纪人是证券 / 期货 / 外汇经纪人
                    'company': self.company,  # 企业名称
                    'location': location,  # 所在城市
                    'industry': 'IT互联科技行业',  # 企业所在行业
                    'keywords': [],  # 此岗位的搜索关键字
                    'platform': 'offical',  # 针对官网抓取时此处一律保存为offical
                    'searchKeyword': '',  # 搜索的关键字，由于是官网抓取所以此处一律为空字符串
                    'description': description,  # 职位的详细描述，包括职责、要求之类的
                    'subIndustry': '',  # 一律为空字符串
                    'stime': datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')  # 抓取时间
                }
                print(item['company'], item['name'])
                if not offical_posts_coll.find_one({'name': item['name'], 'company': item['company'], 'location': item['location']}):
                    offical_posts_coll.insert_one(item)


POST()
